package com.chen.controller.dto;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;

import com.alibaba.fastjson.JSONObject;
import com.chen.common.Result;
import com.chen.entity.bean.Constants;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;

import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;



/**
 * @author chenchao
 * @date 2022/10/15 11:20
 */
@Slf4j
@RestController
@Api(value = "WeiBoController",tags = "微博登录")
public class WeiBoController {
   public   String  uuid=UUID.randomUUID().toString().replaceAll("-","");
    @GetMapping("/getUrl")
    public Result getUrl(  HttpSession session){
        //用于第三方应用防止CSRF攻击

//       String uuid=UUID.randomUUID().toString().replaceAll("-","");
       session.setAttribute("state",uuid);
       String url= Constants.WEIBO_URL+"&state="+uuid;
       return Result.success(url);

    }



    @GetMapping("/authWeibo")
    public Result authWeibo(String code,HttpServletRequest request,HttpServletResponse response) {
        //定义token以及失效时间等
        String accessToken;
        String uid;
        // 获取token,获取用户信息
        JSONObject token, userInfo;
        //获取token
        token = getAccessToken(code,request,response);
        accessToken = token.getString("access_token");
        System.out.println(accessToken);
        uid = token.getString("uid");
        // 获取用户信息
        userInfo = getUserInfo(accessToken, uid);
        String id = userInfo.getString("id");
        String profileImageUrl = userInfo.getString("profile_image_url");

        return Result.success(userInfo);
    }

    /**
     * 获取AccessToken
     *
     * @param code 微博返回临时获取token令牌
     * @return 返回数据 { "access_token": "ACCESS_TOKEN", "expires_in": 1234, "remind_in":"798114","uid":"12341234" }
     */
    private JSONObject getAccessToken(String code,HttpServletRequest request,HttpServletResponse response) {
//        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
//        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
//        HttpServletResponse response = ((ServletRequestAttributes) requestAttributes).getResponse();
        response.setContentType("text/html; charset=utf-8");  // 响应编码


        HttpSession session = request.getSession();
        String state = request.getParameter("state");
        System.out.println(uuid);
        if(state.equals(uuid)){
            System.out.println("相同");
        }
//        String uuid = (String) session.getAttribute("state");
        String params =
                "grant_type=authorization_code"
                        + "&client_id="
                        + Constants.WEIBO_CLIENT_ID
                        + "&client_secret="
                        + Constants.WEIBO_CLIENT_SECRET
                        + "&redirect_uri="
                        + Constants.WEIBO_REDIRECT_URI
                        + "&code="
                        + code;
        //得到本次请求服务器结果
        String result = HttpUtil.post(Constants.WEIBO_GET_TOKEN_URL, params);
        HttpResponse execute = HttpRequest.get("https://api.weibo.com/2/users/show.json").form(params).timeout(2000).execute();
        System.out.println(execute);
        return JSONObject.parseObject(result);
    }

    /**
     * 获取用户信息
     *
     * @param accessToken 临时授权访问资源的token
     * @param uid         查询的用户ID
     * @return UserInfo JSON 返回参数：查看http://open.weibo.com/wiki/2/users/show
     */
    private JSONObject getUserInfo(String accessToken, String uid) {
        String params = "?access_token=" + accessToken + "&uid=" + uid;
        String result = HttpUtil.get(Constants.WEIBO_GET_USER_INFO + params);
        return JSONObject.parseObject(result);
    }

}



